/**
 * 1. Promise串行
 *  - 不使用async/await 或 迭代器Generator
 */
const Task = (result, isSuccess = true) => {
  return () =>
    new Promise((resolve, reject) => {
      setTimeout(() => {
        if (isSuccess) {
          console.log(`success: ${result}`)
          resolve(result)
        } else {
          console.log(`error: ${result}`)
          reject(result)
        }
      }, 1000)
    })
}

execute([Task('A'), Task('B'), Task('X', false), Task('C')]).then(
  resultList => {
    // 这里期望打印 ["A", "B", null, "C"]
    console.log(resultList)
  }
)

function execute(tasks) {
  let resultList = []
  return tasks
    .reduce(
      (previousPromise, currentPromise) =>
        previousPromise.then(resultList => {
          return new Promise(resolve => {
            currentPromise()
              .then(result => {
                resultList.push(result)
                resolve()
              })
              .catch(() => {
                resultList.push(null)
                resolve(resultList.concat(null))
              })
          })
        }),
      Promise.resolve()
    )
    .then(() => resultList)
}
